/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

#include "Compatibility/I2CHardwareCompatibillity.h"
#include "../../Utils/Utils.h"



#define TWSR_PRESCALER_MASK 	(uint8_t)(~TW_STATUS_MASK)



namespace Coms
{

namespace I2C
{

I2CHardware::I2CHardware(uint8_t callbackVectorNumber, IOAddress twdr, IOAddress twbr, IOAddress twcr, IOAddress twsr, IOAddress twar):
CallbackConnector(callbackVectorNumber), twdr(twdr), twbr(twbr), twcr(twcr), twsr(twsr), twar(twar)
{
	setBitRate();
	setSlaveAddress();
}

I2CHardware::~I2CHardware()
{
	// TODO Auto-generated destructor stub
}


size_t I2CHardware::setBitRate(uint8_t finePrescaler, Prescaler coarsePrescaler)
{
	*twbr = finePrescaler;
	setConfig(twsr,  TWSR_PRESCALER_MASK, coarsePrescaler);

	return F_CPU / (16 - 2 * finePrescaler * pow(4, coarsePrescaler));
}

void I2CHardware::setSlaveAddress(uint8_t address7bit, bool answerGeneralCalls)
{
	*twar = address7bit << 1; //the address occupy the register's MSBits

	if(answerGeneralCalls)
		setBit(*twar, TWGCE);		//answering general calls
}

}

}
